#include "window.h"
#include "nstring.h"
#include "platform.h"

#include <string>
#include <stdexcept>
using namespace std;

#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

/*
*	Entry Point for Win32 Application
*/
extern int main();
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	return main();
}

Window::Window(int formId):
	_handle(nullptr), _formId(formId)
{
}


Window::~Window(void)
{
}

void Window::msgbox(Window* owner, const string& message, const string& title)
{
	HWND parent = owner ? static_cast<HWND>(owner->handle()) : NULL;
	wstring wmessage = a2u(message), wtitle = a2u(title);
	MessageBoxW(parent, wmessage.c_str(), wtitle.c_str(), MB_OK);
}

void* Window::handle() const
{
	return _handle;
}

void Window::show()
{
	DialogBoxParam(GetModuleHandle(NULL), MAKEINTRESOURCE(_formId), NULL,
		[](HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam){
			if (msg == WM_INITDIALOG ) {				
				Window* self = reinterpret_cast<Window*>(lparam);
				self->_handle = hwnd;
				SetWindowLongPtr(hwnd, GWLP_USERDATA, lparam);

				// call the init function
				self->init();

				return TRUE;
			} else {
				Window* self = reinterpret_cast<Window*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
				if (self) {
					return self->proc(msg, reinterpret_cast<void*>(wparam), reinterpret_cast<void*>(lparam));
				} else {
					return FALSE;
				}
			}			
	}, reinterpret_cast<LPARAM>(this));
}

int Window::proc(unsigned int msg, void* wparam, void* lparam)
{
	return DefWindowProc(
		static_cast<HWND>(this->_handle), 
		msg, 
		reinterpret_cast<WPARAM>(wparam), 
		reinterpret_cast<LPARAM>(lparam));
}

void Window::close()
{
	EndDialog(static_cast<HWND>(this->_handle), 0);
}